import os
import time

from pykeyboard import PyKeyboard
from pymouse import PyMouse

from utils.base_util import CommonUtils


class ImgMatchUtil:

    mouse = PyMouse()
    keyboard = PyKeyboard()


    @classmethod
    def match_img(cls, target):
        image_path = CommonUtils.get_abs_path_single("img")
        template_path = os.path.join(image_path, target)
        screen_path = os.path.join(image_path, 'screen.png')
        from PIL import ImageGrab
        ImageGrab.grab().save(screen_path)
        time.sleep(1)
        import cv2
        # 读取大图
        screen = cv2.imread(screen_path)
        # 读取小图
        template = cv2.imread(template_path)
        # 调用匹配算法
        result = cv2.matchTemplate(screen, template, cv2.TM_CCOEFF_NORMED)

        min, max, min_loc, max_loc = cv2.minMaxLoc(result)

        # 计算矩形十字中心点的坐标
        x = max_loc[0] + int(template.shape[1] / 2)
        y = max_loc[1] + int(template.shape[0] / 2)

        # 如果没匹配成功，则返回的是-1，-1
        return x,y

        # 单击图片元素
    @classmethod
    def click_image(cls, target):
        x, y = cls.match_img(target)
        if x == -1 and y == -1:
            return
        cls.mouse.click(x, y)

    @classmethod
    def do_click_image(cls, x, y):
        cls.mouse.click(x, y)

    # 双击图片元素
    @classmethod
    def double_click_image(cls, target):
        x, y = cls.match_img(target)
        if x == -1 and y == -1:
            return
        cls.mouse.click(x, y, n=2)

    # 向一个文本框图片输入
    @classmethod
    def input_image(cls, target, value):
        x, y = cls.match_img(target)
        if x == -1 and y == -1:
            return
        cls.keyboard.type_string(value)

if __name__ == '__main__':
    x,y = ImgMatchUtil.match_img('add_button.PNG')
    print(x,y)
    ImgMatchUtil.do_click_image(x, y)
    ImgMatchUtil.do_click_image(y, x)